/*
 * KIMWONSORK@GMAIL.COM
 * COPYRIGHT CRAYONSOFT All rights reserved.
 * 2013오후 9:07:00
 * kws
 */

package com.crayon.account.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.Toast;

import com.crayon.account.dao.DAOFood;
import com.crayon.account.dao.DAOPhotos;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.account.impl.OnDialogFragment;
import com.crayon.sharemenu.R;
import com.crayon.util.ActivityCameraCrop;
import com.crayon.util.ActivityImageViewer;
import com.crayon.util.GDB;
import com.crayon.util.UIBIND;
import com.crayon.util.UTILCurrency;
import com.crayon.util.UTILDate;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.Where;

import net.fortuna.ical4j.model.Recur;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * com.crayon.account.fragments.FRGWrite
 * @author kws
 *
 */

//public class FragmentRGWrite extends Fragment{
//}

public class FragmentWriteFood extends Fragment
        implements View.OnClickListener
,DatePickerDialog.OnDateSetListener,CompoundButton.OnCheckedChangeListener
{

	public interface OnFoodAppendAction{
		public void OnActionCallCamera(DAOFood food);
	}
	OnFoodAppendAction onFoodAppendAction=null;

	public OnFoodAppendAction getOnFoodAppendAction() {
		return onFoodAppendAction;
	}

	public void setOnFoodAppendAction(OnFoodAppendAction onFoodAppendAction) {
		this.onFoodAppendAction = onFoodAppendAction;
	}

	public DAOFood getTbFood() {
		return tbFood;
	}

	public void setTbFood(DAOFood tbFood) {
		this.tbFood = tbFood;
	}

	DAOFood tbFood=new DAOFood();
    @Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if(getArguments()!=null){
			DAOFood item = (DAOFood) getArguments().getSerializable(PARAM_DAO);
			tbFood = item==null ? new DAOFood(): item;
		}
		super.onCreate(savedInstanceState);
	}

    public static final String PARAM_DAO = "itemical";
    public static FragmentWriteFood onCreateInstance(Bundle bundle){
		FragmentWriteFood f = new FragmentWriteFood();
		f.setArguments(bundle);
		return f;
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_write_fooditem,container, false);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		UIBIND.bindText(getView(), R.id.topTitleName,getString(R.string.activity_title_write_household));
		UIBIND.bindButton(getView(), R.id.buttonTopRight, getString(R.string.button_text_save));

		UIBIND.bindViewVisible(getView(), R.id.topButtonBack, true);

		UIBIND.bindView(getView(), R.id.topButtonBack,this);
		UIBIND.bindView(getView(), R.id.buttonTopRight,this);
		UIBIND.bindView(getView(), R.id.buttonCategory, this);
		UIBIND.bindView(getView(), R.id.buttonCardBank,this);
		UIBIND.bindView(getView(), R.id.buttonTopModify,this);
		UIBIND.bindView(getView(), R.id.buttonDelete, this);
		UIBIND.bindView(getView(), R.id.topButtonSave, this);
		UIBIND.bindView(getView(), R.id.buttonTopCamera,this);
		UIBIND.bindView(getView(), R.id.buttonImageDelete,this);



		if(tbFood!=null && tbFood.getId()>0){
			UIBIND.bindViewVisible(getView(), R.id.topButtonSave, false);
			UIBIND.bindViewVisible(getView(), R.id.buttonTopModify, true);
			UIBIND.bindViewVisible(getView(), R.id.buttonDelete, true);
		}else{
			UIBIND.bindViewVisible(getView(), R.id.topButtonSave, true);
			UIBIND.bindViewVisible(getView(), R.id.buttonTopModify, false);
			UIBIND.bindViewVisible(getView(), R.id.buttonDelete, false);
//
		}
		UIBIND.bindText(getView(), R.id.textSummary, tbFood.getSummary());
		UIBIND.bindText(getView(), R.id.textPrice, UTILCurrency.formatCurrencyPrice(tbFood.getPrice()));
		UIBIND.bindText(getView(), R.id.textDescription, tbFood.getDesc());
		UIBIND.bindText(getView(), R.id.textUseCate, tbFood.getCategory());
		UIBIND.bindView(getView(), R.id.photoImageView,this);

		if(tbFood.getUri()!=null){

			try {
//				DAO
//				UIBIND.bindImageViewBitmapArray(getView(), R.id.photoImageView, getDaoAccount().getxImage());
				UIBIND.bindViewVisible(getView(), R.id.buttonImageDelete, true);
			} catch (Exception e) {
//				// TODO: handle exception
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
//		case R.id.buttonImageDelete:
//			if(getDaoAccount()!=null && getDaoAccount().getxImage()!=null){
//				getDaoAccount().setxImage(null);
//				getDaoAccount().setxImageKey(null);
//				UIBIND.bindViewVisible(getView(), R.id.buttonImageDelete, false);
//				UIBIND.bindImageViewBitmap(getView(), R.id.photoImageView, null);
//			}
//			break;
//		case R.id.photoImageView:
//			byte[] data = getDaoAccount().getxImage();
//			if(data!=null && data.length>0){
//				Intent intent= new Intent(getActivity(),ActivityImageViewer.class);
//				intent.putExtra(ActivityImageViewer.PARAM_IMAGE, getDaoAccount().getxImage());
//				intent.putExtra(ActivityImageViewer.PARAM_URI, getDaoAccount().getxImageKey());
//				startActivityForResult(intent, 0x01);
//			}
//			break;
		case R.id.buttonTopCamera:

//			if(getOnFoodAppendAction()!=null){
//				getOnFoodAppendAction().OnActionCallCamera(tbFood);
//			}
			Intent intent= new Intent(getActivity()
					,ActivityCameraCrop.class);
			intent.putExtra(ActivityCameraCrop.PARAM_UUID, tbFood.getUuid());
			startActivityForResult(intent, 0x00);

			break;

		case R.id.buttonDelete:
			new AlertDialog.Builder(getActivity()).setMessage(R.string.alertmsg_write_delete_ask).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			}).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					deleteJustThis();

				}
			}).create().show();

			break;
		case R.id.topButtonSave:
		case  R.id.buttonTopRight:
//
			GDB.log(getClass(), "@@ save ");
			try {
				saveModyNoRuleOne();
			} catch (Exception e) {
				// TODO: handle exception
				GDB.log(getClass(), "err save " + e.getMessage());
			} finally{

			}

			break;
//		case R.id.buttonTopModify:
//			if(!bindTextTodaoItem()){
//				return;
//			}
//			if(getDaoDB().getRecur()==null){
//				try {
//					saveModyNoRuleOne();
//
//				} catch (Exception e) {
//					// TODO: handle exception
//				} finally{
//					getActivity().onBackPressed();
//					if(getOnDialogFragment()!=null){
//						getOnDialogFragment().onDismissDialog(this);
//					}
//				}
//
//			}else{
//
//				//전체수정  , 이후모두 수정, 이이벤트만 수정 옵션처리.
//				AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
//				builderSingle.setIcon(R.drawable.ic_launcher);
//				builderSingle.setTitle("Select One Name:-");
//				final ArrayAdapter<String> arrayAdapterModify = new ArrayAdapter<String>(
//						getActivity(),
//						android.R.layout.select_dialog_singlechoice);
//				final String[] itemModify=getResources().getStringArray(R.array.write_modify_option);
//				for(String item: itemModify) arrayAdapterModify.add(item);
//				builderSingle.setNegativeButton("cancel",
//						new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
//					}
//				});
//
//				builderSingle.setAdapter(arrayAdapterModify,
//						new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						String selected = arrayAdapterModify.getItem(which);
//						if(selected!=null){
//							try {
//								if(selected.equals(getString(R.string.option_modify_all))){
//									saveModifyAll();
//								}else if(selected.equals(getString(R.string.option_modify_all_afterthis))){
//									saveModifyAllAtterThis();
//								}else if(selected.equals(getString(R.string.option_modify_onlythis))){
//									saveModifyJustThis();
//								}else{
//
//								}
//
//							} catch (Exception e) {
//								// TODO: handle exception
//							} finally{
//								dialog.dismiss();
//								getActivity().onBackPressed();
//								if(getOnDialogFragment()!=null){
//									getOnDialogFragment().onDismissDialog(FragmentWriteFood.this);
//								}
//							}
//						}
//
//					}
//				});
//				builderSingle.show();
//			}
//
//			break;
		case R.id.topButtonBack:
			if(getParentFragment() instanceof DialogFragment){
				((DialogFragment) getParentFragment()).dismiss();;
			}

			getActivity().onBackPressed();
			break;
//
		}
	}


	private void setUntilDateWithRule(){

	}
	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// TODO Auto-generated method stub
	}

//	@Override
//	public List<RadioButton> OnSupportItems() {
//		// TODO Auto-generated method stub
//		LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);;
//		List<RadioButton> items =new ArrayList<RadioButton>();
//		for(ERuleTypes types : ERuleTypes.values()){
//			RadioButton button = (RadioButton)inflater.inflate(R.layout.radiobutton_item, null);
//			button.setId(types.getKey());
//			button.setText(getString(types.getNameId()));
//			items.add(button);
//		}
//		return items;
//
//	}

//	@Override
//	public void OnRadioCheckedListner(RadioGroup group, int checkedId) {
//		// TODO Auto-generated method stub
//		for(ERuleTypes types : ERuleTypes.values()){
//			if(types.getKey()==checkedId){
//				GDB.log(getClass(), "반복프리퀜시 설정하기 선택" + types.getRecur());
//				UIBIND.bindButton(getView(), R.id.buttonRRule, getString(types.getNameId()));
//				try {
//					Recur recur = new Recur(Recur.DAILY);
//					recur.setFrequency(types.getRecur());
//					GDB.log(getClass(), "반복프리퀜시 설정하기 값" + recur.toString());
//					getDaoAccount().setRecur(recur.toString());
//
//				} catch (Exception e) {
//					// TODO: handle exception
//					GDB.log(getClass(), "ERR 프리퀜시 설정" + e.getMessage());
//				}
//				break;
//			}
//		}
//
//		//		TextSwitcher switcher =new TextSwitcher(getActivity());
//
//	}




	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

//
//		if(getDaoAccount()!=null && getArguments()!=null){
//
//			RadioGroup radoiGroupIoType = (RadioGroup)UIBIND.bindView(getView(), R.id.radoiGroupIoType);
//			if(getDaoAccount().getId()>0){
//				DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//				try {
//					setDaoDB(baseManager.getDAOAccount().queryForId(getDaoAccount().getId()));
//				} catch (Exception e) {
//					// TODO: handle exception
//				}
//				radoiGroupIoType.setVisibility(View.GONE);
//
//			}
//			GDB.log(getClass(), "summary " + getDaoAccount().getSummary());
//			GDB.log(getClass(), "price " + getDaoAccount().getXprice());
//
//			UIBIND.bindText(getView(), R.id.textSummary, getDaoAccount().getSummary());
//			if(getDaoAccount().getXprice()>0)
//				UIBIND.bindText(getView(), R.id.textPrice, UTILCurrency.formatPrice(getDaoAccount().getXprice()));
//			UIBIND.bindText(getView(), R.id.buttonDtStart, UTILDate.getYYYYMMDD(getDaoAccount().getDtStart()));
//		}
//

//		if(getDaoAccount()!=null && getDaoAccount().getUuid()!=null){
//			DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//			try {
//				Where<DAOPhotos,Integer> where = baseManager.getDAOPhotos().queryBuilder().where();
//				where.eq("uuid", getDaoAccount().getUuid());
//				List<DAOPhotos> photos = where.query();
//				if(photos!=null &&photos.size()>0){
//					for(DAOPhotos item : photos){
//						byte[] bitmaps = item.getArrays();
//						Bitmap bitmap = BitmapFactory.decodeByteArray(bitmaps,0,bitmaps.length);
//						getDaoAccount().setxImage(Arrays.copyOf(bitmaps, bitmaps.length));
//						UIBIND.bindImageViewBitmap(getView(), R.id.photoImageView, bitmap);
//						break;
//					}
//				}
//			} catch (Exception e) {
//				// TODO: handle exception
//			}
//
//			//photoImageView
//		}
	}

	private void actionDelete(){
//		try {
//			DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
//			dao.delete(getDaoAccount());
//		}catch (Exception e) {
//			// TODO: handle exception
//		}finally{
//			getActivity().onBackPressed();
//			if(getOnDialogFragment()!=null){
//				getOnDialogFragment().onDismissDialog(this);
//
//			}
//
//		}
	}


	private boolean bindTextTodaoItem(){
//		getDaoAccount().setSummary(UIBIND.getTextValue(getView(), R.id.textSummary));
//		getDaoAccount().setXprice(UIBIND.getTextValueNumber(getView(), R.id.textPrice));
//		getDaoAccount().setDesciption(UIBIND.getTextValue(getView(), R.id.textDescription));
//		getDaoAccount().setxCategory(UIBIND.getTextValue(getView(), R.id.textUseCate));
//		getDaoAccount().setXaccountName(UIBIND.getTextValue(getView(), R.id.textCardBank));
//
//		if(getDaoAccount().getSummary()==null){
//			Toast.makeText(getActivity(), getString(R.string.toast_message_need_title), Toast.LENGTH_SHORT).show();
//			return false;
//		}
//		if(getDaoAccount().getXprice()==0){
//			Toast.makeText(getActivity(),getString(R.string.toast_message_need_price) , Toast.LENGTH_SHORT).show();
//			return false;
//		}
//
//
//		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//		//카테고리 추가.
//		try {
//			if(getDaoAccount().getxCategory()!=null){
//				Dao<DAOCategory,Integer> daoCate = baseManager.getDAOCategory();
//				RadioGroup radoiGroupIoType = (RadioGroup)UIBIND.bindView(getView(), R.id.radoiGroupIoType);
//				if(radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeIn){
//					daoCate.createIfNotExists(new DAOCategory(DAOCategory.INCOM,getDaoAccount().getxCategory()));
//				}else if(radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeOut){
//					daoCate.createIfNotExists(new DAOCategory(DAOCategory.OUTCOM,getDaoAccount().getxCategory()));
//				}
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
		return true;
	}

	private void saveModyNoRuleOne() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			Dao<DAOFood, Integer> dao =  baseManager.getDAOFood();
			GDB.log(getClass(), "tbFood.getId() " + tbFood.getId());
			tbFood.setSummary(UIBIND.getTextValue(getView(), R.id.textSummary));
			tbFood.setPrice(UIBIND.getTextValueNumber(getView(), R.id.textPrice));
			tbFood.setDesc(UIBIND.getTextValue(getView(), R.id.textDescription));
			tbFood.setCategory(UIBIND.getTextValue(getView(), R.id.textUseCate));
			if(tbFood.getSummary()==null || StringUtils.isEmpty(tbFood.getSummary())){
				Toast.makeText(getActivity(), getString(R.string.toast_message_need_title), Toast.LENGTH_SHORT).show();
				return;
			}

			if (tbFood.getId()>0){
				dao.update(tbFood);
			}else{
				dao.create(tbFood);
			}
			List<DAOFood> list = dao.queryForAll();
			for(DAOFood item : list){
				GDB.log(getClass(), "item " + item.getSummary() +"\t" + item.getPrice() +"\t" );
			}


			getActivity().onBackPressed();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	//UUID가 똑 같은 모든 것을 수정한다.
	private void saveModifyAll() throws Exception{
//		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//		try {
//			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
//			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
//
//			dao.update(getDaoAccount());
//
//
//
//		} catch (Exception e) {
//			// TODO: handle exception
//			GDB.log(getClass(), "err 전체 수정 " + e.getMessage());
//		}
	}

	//이후 모든것을 변경한다.
	//원천것을 시작일까지 업데이트 한다.
	//시작일 이후 새로운 이벤트를 생성한다.
	private void saveModifyAllAtterThis() throws Exception{
//		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//		try {
//			//오리지널 데이타를 가져와 untils을 세팅한다.
//			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
//			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
//			if(getDaoDB().getId()>0){
//				if(getDaoDB().getRecur()!=null){
//					getDaoDB().setDtUntil(getDaoAccount().getDtStart());
//					Recur recur = new Recur(getDaoDB().getRecur());
//					recur.setUntil(UTILDate.getConvertICal4jDate(getDaoAccount().getDtStart()));//시작일을 부모의 종료일로 설정한다.
//					getDaoDB().setRecur(recur.toString());
//					GDB.log(getClass(),"이후 이전 것 반복 언틀세팅 " + recur.toString());
//				}
//				dao.update(getDaoDB());
//			}
//			{
//				//
//				GDB.log(getClass(),"이후 모든것 새로운 이벤트 생성");
//				getDaoAccount().setId(0);
//				getDaoAccount().setUuid(getDaoDB().getUuid());
//				dao.create(getDaoAccount());
//			}
//
//		} catch (Exception e) {
//			// TODO: handle exception
//			GDB.log(getClass(), "이후 모든 것 변경에 대한 처리 오류 발생" + e.getMessage());
//
//		}
	}

	/**
	 * 이것만 수정한다.
	 * 1. 제외일을 넣는다.
	 *
	 * @throws Exception
	 */
	private void saveModifyJustThis() throws Exception{
//		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//		try {
//			//오리지널 데이타를 가져와 untils을 세팅한다.
//			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
//			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
//			if(getDaoDB().getId()>0){
//				getDaoDB().addSaveExDate(getDaoAccount().getDtStart());
//				dao.update(getDaoDB());
//			}
//			{
//
//				getDaoAccount().setId(0);
//				getDaoAccount().setUuid(getDaoDB().getUuid());
//				getDaoAccount().setRecur(null);
//				dao.create(getDaoAccount());
//			}
//			List<DAOAccount> list = dao.queryForAll();
//			for(DAOAccount item : list){
//				GDB.log(getClass(), "item " + item.getSummary() +"\t" + item.getXprice() +"\t" + UTILDate.getYYYYMMDD(item.getDtStart()));
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
	}

	private void deleteJustThis() {
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			Dao<DAOFood, Integer> dao =  baseManager.getDAOFood();
			GDB.log(getClass(), "getDaoAccount().getId() " + tbFood.getId());
			if(tbFood.getId()>0){
				dao.delete(tbFood);
			}
//			getActivity().onBackPressed();
			getActivity().finishActivity(0xff);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}




	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
//		if(buttonView.getId()==R.id.checkUntil){
//			if(isChecked==false){
//				UIBIND.bindButton(getView(), R.id.buttonUntil, "");
//				getDaoAccount().setDtUntil(null);
//				setUntilDateWithRule();
//			}
//		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if( activity instanceof  OnFoodAppendAction){
			setOnFoodAppendAction((OnFoodAppendAction)activity);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		GDB.log(getClass(), ">>>>onActivityResult REQUESTCODE_CAMERA " + ActivityCameraCrop.REQUESTCODE_CAMERA);
		GDB.log(getClass(), ">>>>onActivityResult " + requestCode);
		GDB.log(getClass(), ">>>>onActivityResult " + resultCode);
		GDB.log(getClass(), ">>>>onActivityResult " + data);

		if(data!=null){
			DAOPhotos daophoto = (DAOPhotos)data.getSerializableExtra("daophoto");
			tbFood.setUri(daophoto.getUri());
			byte[] imgarr = data.getByteArrayExtra("data");
			if(imgarr!=null &&imgarr.length>0){
				try {
					UIBIND.bindImageViewBitmapArray(getView(), R.id.photoImageView, imgarr);
					UIBIND.bindViewVisible(getView(), R.id.buttonImageDelete, true);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}